#include "motor.h"
#include <stdlib.h>
#include <stdint.h>
/**
 * @brief 函数定义
 *
 */
static void Motor_Driver(Motor *motor, int16_t pwm);

/**
 * @brief 电机初始化
 * @author Sereden
 * @date 2024-8-15
 * @retval None
 *
 */
void Motor_Init(Motor *motor,  TIM_HandleTypeDef *htim_pwm, uint32_t channel,
                GPIO_TypeDef *port1, uint16_t pin1, GPIO_TypeDef *port2, uint16_t pin2) {
  // 绑定函数指针
  motor->Driver = Motor_Driver;

  // 初始化变量
  motor->htim_pwm = htim_pwm;
  motor->channel = channel;
  motor->port1 = port1;
  motor->pin1 = pin1;
  motor->port2 = port2;
  motor->pin2 = pin2;

  // 开启定时器
  HAL_TIM_PWM_Start(motor->htim_pwm, motor->channel);   // pwm输出
}

/**
 * @brief 电机驱动
 * @author Sereden
 * @date 2024-8-15
 * @param value 电机速度
 * @retval None
 *
 */
static void Motor_Driver(Motor *motor, int16_t pwm) {
  if (pwm > 0) {
    // 正转
    HAL_GPIO_WritePin(motor->port1, motor->pin1, GPIO_PIN_SET);
    HAL_GPIO_WritePin(motor->port2, motor->pin2, GPIO_PIN_RESET);
  } else if (pwm < 0) {
    // 反转
    HAL_GPIO_WritePin(motor->port1, motor->pin1, GPIO_PIN_RESET);
    HAL_GPIO_WritePin(motor->port2, motor->pin2, GPIO_PIN_SET);
  } else {
    HAL_GPIO_WritePin(motor->port1, motor->pin1, GPIO_PIN_RESET);
    HAL_GPIO_WritePin(motor->port2, motor->pin2, GPIO_PIN_RESET);
  }
  __HAL_TIM_SET_COMPARE(motor->htim_pwm, motor->channel, abs(pwm));
}



